<template>
  <div>
    <div
      class="h200px relative shadow-[inset_0_68px_35px_rgba(0,0,0,0.5),inset_0_-68px_120px_rgba(0,0,0,0.3)]"
    >
      <GlobalHeader class="color-white"></GlobalHeader>

      <!-- 背景图 -->
      <div
        class="h-full bg-center bg-cover absolute top-0 left-0 w-full z--1"
        :style="{
          backgroundImage: `url(${
            userSkin?.skinFileIdUrl ||
            '/src/assets/img/userHome/header_banner.avif'
          })`,
        }"
      ></div>

      <!-- 个人信息区域 -->
      <div
        class="p-[0px_60px] desktop:p-[0px_140px] w-full h-80px absolute bottom-10px left-0 box-border flex justify-between items-center"
      >
        <!-- 个人信息 -->
        <div flex gap25px items-center>
          <div
            class="w-64px h-64px b-rd-full bg-cover bg-center bg-no-repeat cursor-pointer"
            :style="{
              backgroundImage: `url(${
                userInfo.userVo.avatar || userStore.defaultAvatar
              })`,
            }"
          ></div>
          <div>
            <div>
              <span class="text-24px c-#fff font-700">{{
                userInfo.userVo.nickName
              }}</span>
              <span
                class="c-sky-500 text-25px m-l-10px v-mid"
                :class="`iconfont icon-icon-lv${userInfo.currentUserLevel}`"
              ></span>
            </div>
            <div class="text-12px c-#fff m-t-10px">
              {{ userInfo.signature || "这个人很懒，什么都没有留下" }}
            </div>
          </div>
        </div>

        <!-- 视角切换和皮肤设置 -->
        <div v-if="userId == userStore.userInfo.id.toString()">
          <el-dropdown trigger="click">
            <div
              class="w-150px h34px text-12px c-white b-1px b-solid b-#fff b-rd-4px leading-34px text-center cursor-pointer bg-[rgba(255,255,255,0.2)] hover:bg-[rgba(255,255,255,0.5)]"
            >
              视角：我自己
              <span class="iconfont icon-jiantoubottom v-mid"></span>
            </div>
            <template #dropdown>
              <el-dropdown-menu class="w-150px p-x-10px box-border">
                <el-dropdown-item
                  class="!hover:color-#606266 !b-rd-6px"
                  @click="viewShow(1)"
                >
                  我的粉丝
                </el-dropdown-item>
                <el-dropdown-item
                  class="!hover:color-#606266 !b-rd-6px"
                  @click="viewShow(2)"
                >
                  新访客
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>

          <!-- 皮肤设置 -->
          <span
            @click="skinView"
            class="iconfont icon-pifu text-22px c-#fff b-1px b-solid b-#fff b-rd-4px w-34px h-34px m-l-10px inline-block text-center leading-34px cursor-pointer bg-[rgba(255,255,255,0.2)] hover:bg-[rgba(255,255,255,0.5)]"
          ></span>
        </div>

        <div v-else>
          <el-button
            class="!w-150px !h-34px c-#fff hover:c-#fff"
            color="rgba(255,255,255,0.2)"
            v-if="userInfo.followUser"
            @click="follow(2)"
            :loading="followButLoading"
          >
            已关注
          </el-button>
          <el-button
            class="!w-150px !h-34px c-#fff hover:c-#fff"
            color="#00aeec"
            type="primary"
            @click="follow(1)"
            :loading="followButLoading"
            v-else
          >
            关注
          </el-button>
          <el-button
            class="!w-150px !h-34px c-#fff hover:c-#fff"
            color="rgba(255,255,255,0.2)"
          >
            发消息
          </el-button>
        </div>
      </div>
    </div>

    <!-- label -> 菜单 -->
    <div
      class="p-[0px_60px] desktop:p-[0px_140px] w-full h-64px box-border b-b-1px b-b-solid b-b-#f1f2f3 flex justify-between"
    >
      <el-menu
        default-active="0"
        class="h-full !b-0px flex-1"
        mode="horizontal"
      >
        <el-menu-item
          class="!hover:bg-#fff !bg-#fff"
          v-for="item in menuList"
          :key="item.index"
          :index="item.index"
          @click="selectMenu(item)"
        >
          <span
            :class="`iconfont ${item.icon} font-700 m-r-10px text-18px v-mid`"
          ></span>
          {{ item.label }}
        </el-menu-item>
      </el-menu>

      <div class="flex gap30px text-center items-center text-13px c-#61666d">
        <div>
          <p>关注数</p>
          <p class="c-#18191c">{{ userInfo.followNum }}</p>
        </div>
        <div>
          <p>粉丝数</p>
          <p class="c-#18191c">{{ userInfo.fansNum }}</p>
        </div>
        <div>
          <p>获赞数</p>
          <p class="c-#18191c">{{ userInfoExtVo?.likeCount }}</p>
        </div>
        <div>
          <p>播放数</p>
          <p class="c-#18191c">{{ userInfoExtVo?.playCount }}</p>
        </div>
      </div>
    </div>

    <!-- 组件 -->
    <div class="p-[0px_60px] desktop:p-[0px_140px]">
      <component :is="activeComponent"></component>
    </div>

    <!-- 皮肤设置弹框 -->
    <el-drawer
      v-model="skinViewVisible"
      direction="btt"
      :with-header="false"
      :before-close="handleClose"
      :size="'50%'"
    >
      <el-tabs v-model="activeSkinTabName">
        <el-tab-pane
          v-for="skin in skin_type"
          :key="skin.value"
          :label="skin.label"
          :name="skin.value"
        >
          <div class="grid grid-cols-3 gap-10px p-20px m-b-60px">
            <div
              v-for="item in filteredSkinList(skin.value)"
              :key="item.id"
              class="w-full b-rd-4px relative h-105px group"
              @click="viewSkin(item)"
            >
              <img
                :src="item.skinFileIdUrl"
                class="w-full h-105px b-rd-6px group-hover:rounded-b-0 box-border top-0 left-0 group-hover:z-2 absolute"
                :class="{
                  'b-4px b-solid b-#00aeec  group-hover:b-b-0':
                    userInfo.skinId === item.id,
                }"
              />
              <div
                class="absolute group-hover:rounded-b-6px group-hover:translate-y-75px group-hover:z-1 left-0 top-30px w-full h-75px p-4 flex justify-between items-center box-border shadow bg-white z--1"
                :class="{
                  'b-4px b-solid b-#00aeec box-border group-hover:b-t-0':
                    userInfo.skinId === item.id,
                }"
              >
                <div>
                  <p class="text-16px c-#18191c">{{ item.skinName }}</p>
                  <span class="c-#61666d text-14px">免费</span>
                </div>
                <el-button
                  v-if="userInfo.skinId === item.id"
                  class="!w-130px !h-32px !text-14px"
                >
                  已使用
                </el-button>
                <el-button
                  v-else
                  @click="useSkin(item)"
                  type="primary"
                  class="!w-130px !h-32px !text-14px"
                >
                  使用
                </el-button>
              </div>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </el-drawer>
  </div>
</template>

<script setup lang="ts">
import { useUserStore } from "@/store/userStore";
import {
  computed,
  getCurrentInstance,
  onMounted,
  provide,
  ref,
  shallowRef,
  toRefs,
  type Component,
} from "vue";
import { useRoute } from "vue-router";
import {
  getCardUInfo as getCardUInfoApi,
  getUserInfoExt as getUserInfoExtApi,
} from "@/api/user/user";
import type { UserInfoVo, UserInfoWebExtVo } from "@/api/user/types";
import { listUserSkinInfo } from "@/api/userSkinInfo";
import type { UserSkinInfoVO } from "@/api/userSkinInfo/types";
import { updUserInfo as updUserInfoApi } from "@/api/user/user";
import { addUserFollow as addUserFollowApi } from "@/api/userFollow";
import to from "await-to-js";
import type { UserFollowForm } from "@/api/userFollow/types";
import Home from "./home/index.vue";
import Dynamics from "./dynamics/index.vue";
import Submit from "./submit/index.vue";
import component from "element-plus/es/components/tree-select/src/tree-select-option.mjs";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { skin_type } = toRefs<any>(proxy?.useDict("skin_type") || {});

const route = useRoute();

// 路径参数
const userId = route.params.userId as string;

const userStore = useUserStore();

// 用户信息
const userInfo = ref<UserInfoVo>(userStore.userInfo);

// 控制GlobalHeader组件logo显示
provide("showLogo", true);

// 皮肤设置弹框的显示状态
const skinViewVisible = ref(false);

// 皮肤列表
const skinList = ref<UserSkinInfoVO[]>();

// 用户皮肤信息
const userSkin = ref<UserSkinInfoVO>();

// 当前选中的皮肤标签页
const activeSkinTabName = ref("1");

// 视角查看 type 1: 我的粉丝, 2: 新访客
const viewShow = (type: number) => {};

// 关注按钮加载状态
const followButLoading = ref(false);

// 关注表单
const userFollowForm = <UserFollowForm>{
  followingId: userId,
};

// 当前激活的组件
const activeComponent = shallowRef<Component>(Home);

// 用户附加扩展信息
const userInfoExtVo = ref<UserInfoWebExtVo>();

const menuList = computed(() => [
  { index: "0", label: "主页", icon: "icon-shouye c-#0eb350", component: Home },
  {
    index: "1",
    label: "动态",
    icon: "icon-fengche c-#ff6699",
    component: Dynamics,
  },
  {
    index: "2",
    label: `投稿 ${userInfoExtVo.value?.submitCount || 0}`,
    icon: "icon-tougao c-#00aeec",
    component: Submit,
  },
  {
    index: "3",
    label: `合集 ${userInfoExtVo.value?.collectionCount || 0}`,
    icon: "icon-shujuzhongxin c-#40c5f1",
  },
  {
    index: "4",
    label: `收藏 ${userInfoExtVo.value?.collectCount || 0}`,
    icon: "icon-tuijian c-#ffb027",
  },
  { index: "5", label: "追番追剧", icon: "icon-fensi c-#f85a54" },
  { index: "6", label: "设置", icon: "icon-shezhi c-#00aeec" },
]);

const selectMenu = (sub: any) => {
  if (!sub.component) {
    ElMessage.warning("该功能正在开发中，请耐心等待~");
    return;
  }
  activeComponent.value = sub.component;
};

// 设置皮肤
const skinView = () => {
  skinViewVisible.value = true;
};

// 关闭皮肤设置弹框
const handleClose = () => {
  skinViewVisible.value = false;
  activeSkinTabName.value = "1"; // 重置选中的标签页为经典
};

// 过滤皮肤列表 type 1-经典 2-季节 3-其他
const filteredSkinList = (type: number) => {
  return (skinList.value || []).filter((a) => a.skinType == type);
};

// 获取皮肤列表
const getSkinList = async () => {
  const res = await listUserSkinInfo();
  skinList.value = res.rows;
};

// 皮肤预览
const viewSkin = (skin: UserSkinInfoVO) => {
  userSkin.value = skin;
};

// 皮肤保存
const useSkin = async (skin: UserSkinInfoVO) => {
  await to(
    updUserInfoApi({
      id: userInfo.value.id,
      skinId: skin.id,
    })
  );

  // 更新用户信息中的皮肤ID
  userInfo.value.skinId = skin.id;

  // 更新userStore中的信息
  userStore.userInfo.skinId = skin.id;

  // 关闭皮肤设置弹框
  handleClose();
};

// 关注方法
const follow = async (operateType: number) => {
  followButLoading.value = true;
  userFollowForm.operateType = operateType;
  await addUserFollowApi(userFollowForm);
  followButLoading.value = false;
  userInfo.value.followUser = !userInfo.value.followUser;
};

onMounted(async () => {
  // 如果是查看自己的主页，直接使用userStore中的信息
  if (userId != userInfo.value.id.toString()) {
    let userInfoRes = await getCardUInfoApi(userId);
    userInfo.value = userInfoRes.data;
  }

  // 获取皮肤列表
  await getSkinList();

  if (userInfo.value.skinId) {
    // 如果用户有皮肤ID，设置皮肤
    userSkin.value = skinList.value?.find(
      (skin) => skin.id === userInfo.value.skinId
    );
  }

  // 获取用户扩展附加信息
  const userInfoExtRes = await getUserInfoExtApi(userId);
  userInfoExtVo.value = userInfoExtRes.data;
});
</script>

<style scoped></style>
